package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.*;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysArticleRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysArticleService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 文章业务层处理
 *
 * @author mars
 * @date 2024-03-18
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysArticleServiceImpl implements ISysArticleService {

    private final SysArticleMapper baseMapper;
    private final SysArticleCategoryMapper categoryMapper;
    private final SysUserLikeMapper likeMapper;
    private final SysUserCollectionMapper collectionMapper;
    private final SysUserMapper userMapper;
    private static String classId = "";


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysArticle add(SysArticleRequest request) {
        SysArticle entity = SysArticle.builder().build();
        BeanUtils.copyProperties(request, entity);
        if (request.getCategoryId() != null) {
            String[] split = request.getCategoryId().split(",");
            entity.setCategoryId(split[split.length - 1]);
        }
        if ("0".equals(request.getIsAdmin())) {
            entity.setStatus("1");//普通用户直接发布
        } else {
            entity.setStatus("0");
        }
        entity.setCreateById(ContextUserInfoThreadHolder.get().getId());
        entity.setCreateTime(LocalDateTime.now());
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysArticleRequest request) {
        SysArticle entity = SysArticle.builder().build();
        BeanUtils.copyProperties(request, entity);
        if (request.getCategoryId() != null) {
            String[] split = request.getCategoryId().split(",");
            entity.setCategoryId(split[split.length - 1]);
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysArticle getById(Long id) {
        SysArticle sysArticle = baseMapper.selectById(id);
        String classId = getClassId(Long.valueOf(sysArticle.getCategoryId()));
        if (StringUtils.isBlank(classId)) {
            classId = sysArticle.getCategoryId().toString();
        }
        Long userId = ContextUserInfoThreadHolder.get().getId();
        sysArticle.setCategoryId(classId);
        if (likeMapper.selectCount(new QueryWrapper<SysUserLike>().eq("user_id", userId).eq("article_id", sysArticle.getId())) > 0) {
            sysArticle.setIsLike("1");
        } else {
            sysArticle.setIsLike("0");
        }
        if (collectionMapper.selectCount(new QueryWrapper<SysUserCollection>().eq("user_id", userId).eq("article_id", sysArticle.getId())) > 0) {
            sysArticle.setIsCollect("1");
        } else {
            sysArticle.setIsCollect("0");
        }
        return sysArticle;
    }

    public String getClassId(Long id) {
        SysArticleCategory productClass = categoryMapper.selectById(id);
        if (productClass.getParentId() != 0L) {
            classId = productClass.getParentId().toString() + "," + productClass.getId();
            getClassId(productClass.getParentId());
        }
        return classId;
    }

    @Override
    public PageInfo<SysArticle> pageList(SysArticleRequest request) {
        Page<SysArticle> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysArticle> query = this.buildWrapper(request);
        IPage<SysArticle> pageRecord = baseMapper.selectPage(page, query);
        List<SysArticle> records = pageRecord.getRecords();
        List<SysArticle> recordsNew = new ArrayList<>();
        Long userId = ContextUserInfoThreadHolder.get().getId();
        for (SysArticle article : records) {
            SysArticleCategory category = categoryMapper.selectById(article.getCategoryId());
            article.setCategoryName(category == null ? "" : category.getCategoryName());
            if ("0".equals(article.getStatus())) {
                article.setStatus("未发布");
            } else if ("1".equals(article.getStatus())) {
                article.setStatus("已发布");
            }
            if (likeMapper.selectCount(new QueryWrapper<SysUserLike>().eq("user_id", userId).eq("article_id", article.getId())) > 0) {
                article.setIsLike("1");
            } else {
                article.setIsLike("0");
            }
            if (collectionMapper.selectCount(new QueryWrapper<SysUserCollection>().eq("user_id", userId).eq("article_id", article.getId())) > 0) {
                article.setIsCollect("1");
            } else {
                article.setIsCollect("0");
            }
            SysUser sysUser = userMapper.selectById(article.getCreateById());
            article.setCreateUser(sysUser.getUserName());
            recordsNew.add(article);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysArticle> list(SysArticleRequest request) {
        LambdaQueryWrapper<SysArticle> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysArticle> buildWrapper(SysArticleRequest param) {
        LambdaQueryWrapper<SysArticle> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getTitle())) {
            query.like(SysArticle::getTitle, param.getTitle());
        }
        if (StringUtils.isNotBlank(param.getAuthor())) {
            query.like(SysArticle::getAuthor, param.getAuthor());
        }
        if (param.getCategoryId() != null) {
            query.like(SysArticle::getCategoryId, param.getCategoryId());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysArticle::getStatus, param.getStatus());
        }
        if (StringUtils.isNotBlank(param.getCreateById())) {
            query.eq(SysArticle::getCreateById, param.getCreateById());
        }
        return query;
    }

}
